package com.example.hrsystem.workflow.ui;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hrsystem.R;
import com.example.hrsystem.workflow.WorkflowViewModel;
import com.example.hrsystem.workflow.model.ProcessInstance;
import com.example.hrsystem.workflow.model.WorkflowTask;
import com.google.android.material.textfield.TextInputEditText;

import java.util.ArrayList;
import java.util.List;

/**
 * 工作流执行状态监控界面Activity
 * 用于监控工作流实例的执行状态和任务历史记录
 */
public class WorkflowMonitorActivity extends AppCompatActivity {
    private WorkflowViewModel workflowViewModel;
    private TextInputEditText processInstanceIdEditText;
    private Button queryButton;
    private TextView instanceInfoTextView;
    private TextView currentTaskTextView;
    private TextView executionPathTextView;
    private RecyclerView taskHistoryRecyclerView;
    private TaskHistoryAdapter taskHistoryAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_workflow_monitor);

        // 生成测试数据
        com.example.hrsystem.workflow.TestDataGenerator.generateTestData(this);

        // 初始化ViewModel
        workflowViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication())).get(WorkflowViewModel.class);

        // 初始化UI组件
        initUI();

        // 设置点击事件
        setupClickListeners();
    }

    /**
     * 初始化UI组件
     */
    private void initUI() {
        processInstanceIdEditText = findViewById(R.id.edit_process_instance_id);
        queryButton = findViewById(R.id.button_query);
        instanceInfoTextView = findViewById(R.id.text_instance_info);
        currentTaskTextView = findViewById(R.id.text_current_task);
        executionPathTextView = findViewById(R.id.text_execution_path);
        taskHistoryRecyclerView = findViewById(R.id.recycler_view_task_history);

        // 设置任务历史记录列表
        taskHistoryAdapter = new TaskHistoryAdapter();
        taskHistoryRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        taskHistoryRecyclerView.setAdapter(taskHistoryAdapter);
    }

    /**
     * 设置点击事件
     */
    private void setupClickListeners() {
        queryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                queryProcessInstance();
            }
        });
    }

    /**
 * 查询流程实例
 */
private void queryProcessInstance() {
    String idStr = processInstanceIdEditText.getText().toString().trim();
    if (idStr.isEmpty()) {
        Toast.makeText(this, "请输入流程实例ID", Toast.LENGTH_SHORT).show();
        return;
    }

    try {
        int instanceId = Integer.parseInt(idStr);
        // 调用ViewModel的方法来获取真实的流程实例信息
        loadRealProcessInstanceData(instanceId);
    } catch (NumberFormatException e) {
        Toast.makeText(this, "请输入有效的数字ID", Toast.LENGTH_SHORT).show();
    }
}

    /**
     * 加载真实的流程实例数据
     *
     * @param instanceId 流程实例ID
     */
    private void loadRealProcessInstanceData(int instanceId) {
        // 从ViewModel获取真实的流程实例信息
        ProcessInstance instance = workflowViewModel.getProcessInstanceById(instanceId);
        
        if (instance != null) {
            // 显示流程实例信息
            instanceInfoTextView.setText("实例ID: " + instance.getId() + "\n" +
                    "实例Key: " + instance.getInstanceKey() + "\n" +
                    "名称: " + instance.getName() + "\n" +
                    "状态: " + instance.getStatus() + "\n" +
                    "发起人ID: " + instance.getInitiatorId() + "\n" +
                    "开始时间: " + formatDate(instance.getStartTime()) + "\n" +
                    "结束时间: " + formatDate(instance.getEndTime()));

            // 获取当前任务信息（简化实现，实际应该通过工作流引擎获取）
            currentTaskTextView.setText("当前任务: 需要通过工作流引擎获取");

            // 获取执行路径信息（简化实现）
            executionPathTextView.setText("执行路径: 需要通过工作流引擎获取");

            // 获取任务历史记录
            List<WorkflowTask> taskHistory = workflowViewModel.getTasksByProcessInstance(instanceId);
            // 更新任务历史记录列表
            if (taskHistory != null) {
                taskHistoryAdapter.setTaskHistoryList(taskHistory);
            } else {
                taskHistoryAdapter.setTaskHistoryList(new ArrayList<WorkflowTask>());
            }
        } else {
            Toast.makeText(this, "未找到指定的流程实例", Toast.LENGTH_SHORT).show();
            
            // 清空显示
            instanceInfoTextView.setText("未找到流程实例");
            currentTaskTextView.setText("当前任务: 无");
            executionPathTextView.setText("执行路径: 无");
            taskHistoryAdapter.setTaskHistoryList(new ArrayList<WorkflowTask>());
        }
    }

    /**
     * 格式化日期显示
     *
     * @param date 日期对象
     * @return 格式化后的日期字符串
     */
    private String formatDate(java.util.Date date) {
        if (date == null) {
            return "无";
        }
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }
}